﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonSense.UI.MVVM.EventAggregator
{
    public class EventAggregator : IEventAggregator
    {
        public IDictionary<Type, List<object>> subscribers;

        public EventAggregator()
        {
            this.subscribers = new Dictionary<Type, List<object>>();
        }

        public void Subscribe<TEvent>(IEventSubscriber<TEvent> subscriber)
        {
            Type type = typeof(TEvent);
            if (!this.subscribers.ContainsKey(type))
            {
                this.subscribers.Add(type, new List<object>());
            }
            
            if (!this.subscribers[type].Contains(subscriber))
            {
                this.subscribers[type].Add(subscriber);
            }
        }

        public void Unsubscribe<TEvent>(IEventSubscriber<TEvent> subscriber)
        {
            Type type = typeof(TEvent);
            if (this.subscribers.ContainsKey(type))
            {
                this.subscribers[type].Remove(subscriber);
                if (!this.subscribers[type].Any())
                {
                    this.subscribers.Remove(type);
                }
            }
        }

        public void Notify<TEvent>(TEvent eventData)
        {
            Type type = typeof(TEvent);
            if (this.subscribers.ContainsKey(type))
            {
                List<object> subscribersList = this.subscribers[type];
                foreach (object subscriber in subscribersList)
                {
                    IEventSubscriber<TEvent> typedSubscriber = (IEventSubscriber<TEvent>)subscriber;
                    typedSubscriber.Notify(eventData);
                }
            }
        }
    }
}
